import 'dart:async';

import 'package:geolocation/geolocation.dart';
import 'package:geolocation/models/position.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

import 'index.dart';


typedef GeolocatorHelperCallback = void Function(GeoPosition result);

/// 定位工具类
class GeolocatorHelper {


  // 是否单次定位 单次定位 返回结果的时候直接停止
  final bool isSingleLocation;

  final GeolocatorHelperCallback callback;


  StreamSubscription<GeoPosition>? _positionStream;

  GeolocatorHelper({required this.callback, this.isSingleLocation = false});

  /// 关闭定位
  Future<void> stopLocation() async {
    await _positionStream?.cancel();
    _positionStream = null;
  }

  /// 开始定位
  Future<void> startLocation() async {
    bool permission = await _requestPermission();
    if (!permission) {
      OLogger.e('没有权限，无法定位！');
      Loading.showError('attendance_location_permission_not_allow'.tr);
      return;
    }
    if (isSingleLocation) {
      _singleLocation();
    } else {
      _seriesLocation();
    }
  }

  /// 计算距离
  double distanceInMeters(double startLatitude, double startLongitude, double endLatitude, double endLongitude) {
    GeoPosition start = GeoPosition(latitude: startLatitude, longitude: startLongitude);
    GeoPosition end = GeoPosition(latitude: endLatitude, longitude: endLongitude);
    double distanceInMeters = Geolocation.distanceBetween(start, end);
    if (distanceInMeters < 0) {
      distanceInMeters = 0 - distanceInMeters;
    }
    return distanceInMeters;
  }

  

  /// 单次定位
  Future<void> _singleLocation() async {
    final position =  await  Geolocation.getCurrentPosition();
    if (position != null) {
      callback(position);
      OLogger.i('单次定位： $position');
    }
  }

  /// 连续定位
  Future<void> _seriesLocation() async {
    await stopLocation();
    _positionStream = Geolocation.getPositionStream().listen((position) { 
       callback(position);
       OLogger.d(
          "定位信息, longitude: ${position.longitude} , latitude: ${position.latitude}, address:${position.address}");
    });
    OLogger.i('开始连续定位');
  }
 
  
  /// 请求权限
  Future<bool> _requestPermission() async {
    var status = await Permission.location.status;
    if (status == PermissionStatus.granted) {
      return true;
    } else {
      status = await Permission.location.request();
      if (status == PermissionStatus.granted) {
        return true;
      }
    }
    return false;
  }
}